﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IBRx
{
    public static class RxExtensions
    {
        public static IObservable<T> WithCachedSnapshot<T, TKey>(
        this IObservable<T> source,
        Func<T, TKey> keySelector)
            {
                var cache = new Dictionary<TKey, T>();
                return Observable.Defer(() =>
                {
                    lock (cache)
                        return cache.Values.ToList().ToObservable();
                })
                    .Concat(source.Do(s =>
                    {
                        lock (cache) cache[keySelector(s)] = s;
                    }));
            }
    }

}
